import React, { useEffect, useState } from 'react'
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

export default function NewsEditor(props) {
  useEffect(() => {

    const html = props.content
    // 这样写，是为了兼容-新闻更新页面
    if (html === undefined) return
    // 下面是将数据库的html片段，转换成js的步骤，文档上CV即可
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      setEditorState(editorState)
    }
    // 这里用了依赖，主要是，父组件发送异步请求，会有耗时的状况，content有可能为undefined，请求的数据回来时，content会有变化，富文本组件里才有内容
  }, [props.content])

  const [editorState, setEditorState] = useState("")
  return (
    <div>
      <Editor
        editorState={editorState}
        toolbarClassName="aaaaa"
        wrapperClassName="bbbbb"
        editorClassName="ccccc"
        onEditorStateChange={(editorState) => setEditorState(editorState)}

        onBlur={() => {
          // console.log()

          props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
        }}
      />
    </div>
  )
}
